/**
 * 2012-7-8
 * jqsl2012@163.com
 */
package net.jeeshop.web.action.manage.indexNews;

import net.jeeshop.core.Services;
import net.jeeshop.core.dao.page.PagerModel;
import net.jeeshop.core.front.SystemManager;
import net.jeeshop.core.system.bean.User;
import net.jeeshop.services.front.indexnews.IndexNewsService;
import net.jeeshop.services.manage.catalog.CatalogService;
import net.jeeshop.services.manage.indexImg.IndexImgService;
import net.jeeshop.services.manage.indexnews.bean.IndexNews;
import net.jeeshop.services.manage.news.NewsService;
import net.jeeshop.services.manage.news.bean.News;
import net.jeeshop.web.action.BaseController;
import net.jeeshop.web.util.LoginUserHolder;
import net.jeeshop.web.util.RequestHolder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 文章管理
 * @author huangf
 * @author dylan
 * 
 */
@Controller
@RequestMapping("/manage/indexnews/")
public class IndexNewsAction extends BaseController<IndexNews> {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(IndexNewsAction.class);
    private static final String page_toList = "/manage/indexnews/indexnewsList";
    private static final String page_toEdit = "/manage/indexnews/indexnewsEdit";
    private static final String page_toAdd = "/manage/indexnews/indexnewsEdit";

    private IndexNewsAction() {
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }

	@Autowired
	private net.jeeshop.services.manage.indexnews.IndexNewsService indexNewsService;

	@Override
	public Services<IndexNews> getService() {
		return indexNewsService;
	}

    //修改文章
    @Override
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(HttpServletRequest request, IndexNews e, RedirectAttributes flushAttrs) throws Exception {
        String type = e.getType();
        if (!StringUtils.isBlank(type) && type.equals("公益项目")){
            e.setType("public");
        } else {
            e.setType("notice");
        }
        Set<String> contents = getImgStr(e.getContent());
        Iterator it = contents.iterator();
        if (it.hasNext()){
            e.setImgpath((String) it.next());
        }
        getService().update(e);
        return "redirect:toEdit2?id="+e.getId();
    }

    //列表页面点击 编辑商品
    @RequestMapping(value = "toEdit")
    public String toEdit(IndexNews e, ModelMap model) throws Exception {
        return toEdit0(e, model);
    }

    // 添加或编辑商品后程序回转编辑
    @RequestMapping(value = "toEdit2")
    public String toEdit2(IndexNews e, ModelMap model) throws Exception {
        return toEdit0(e, model);
    }

    @RequestMapping(value = "toEdit0")
    private String toEdit0(IndexNews e, ModelMap model) throws Exception {
        model.addAttribute("catalogsArticle", SystemManager.getInstance().getCatalogsArticle());
        return super.toEdit(e, model);
    }

    //新增或者修改后文章的状态要重新设置为未审核状态
    @Override
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public String insert(HttpServletRequest request, IndexNews e, RedirectAttributes flushAttrs) throws Exception {
        logger.error("NewsAction code = " + e.getCode());
        User user = LoginUserHolder.getLoginUser();
        e.setCreateAccount(user.getUsername());
        //未审核
        e.setId(null);
        String type = e.getType();
        if (!StringUtils.isBlank(type) && type.equals("公益项目")){
            e.setType("public");
        } else {
            e.setType("notice");
        }
        Set<String> contents = getImgStr(e.getContent());
        Iterator it = contents.iterator();
        if (it.hasNext()){
            e.setImgpath((String) it.next());
        }
        e.setStatus(IndexNews.news_status_n);
        try{
            getService().insert(e);
        } catch (Exception e1){
            logger.error("insert语句出现异常");
        }
        return "redirect:toEdit2?id="+e.getId();
    }

    //利用正则表达式获取img
    public static Set<String> getImgStr(String htmlStr) {
        Set<String> pics = new HashSet<>();
        String img = "";
        Pattern image;
        Matcher matImage;
        //"<img.*src=(.*?)[^>]*?>" //图片链接地址
        String regImg = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        image = Pattern.compile
                (regImg, Pattern.CASE_INSENSITIVE);
        matImage = image.matcher(htmlStr);
        while (matImage.find()) {
            // 得到<img />数据
            img = matImage.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }

    @RequestMapping(value = "updateStatusY", method = RequestMethod.POST)
    public String updateStatusY(String[] ids, String type, RedirectAttributes flushAttrs) throws Exception {
        indexNewsService.updateStatus(ids,IndexNews.news_status_y);
        addMessage(flushAttrs, "操作成功!");
        return "redirect:selectList";
    }

    //审核未通过,记录将不会出现在门户上
    @RequestMapping(value = "updateStatusN", method = RequestMethod.POST)
    public String updateStatusN(String[] ids, String type, RedirectAttributes flushAttrs) throws Exception {
        indexNewsService.updateStatus(ids,IndexNews.news_status_n);
        addMessage(flushAttrs, "操作成功!");
        return "redirect:selectList";
    }

    //显示指定的文章
    @RequestMapping(value = "up")
    public String up(IndexNews e, RedirectAttributes flushAttrs) throws Exception {
        return updateDownOrUp0(e, IndexNews.news_status_y, flushAttrs);
    }

    //不显示指定的文章
    @RequestMapping(value = "down")
    public String down(IndexNews e, RedirectAttributes flushAttrs) throws Exception {
        return updateDownOrUp0(e, News.news_status_n, flushAttrs);
    }

    private String updateDownOrUp0(IndexNews e, String status, RedirectAttributes flushAttrs) throws Exception {
        if(StringUtils.isBlank(e.getId())){
            throw new NullPointerException("参数不能为空！");
        }
        IndexNews news = new IndexNews();
        news.setId(e.getId());
        news.setStatus(status);
        indexNewsService.updateDownOrUp(news);
        addMessage(flushAttrs, "更新成功!");
        return "redirect:toEdit2?id="+e.getId();
    }

    //检查文章code的唯一性
    @RequestMapping(value = "unique")
    @ResponseBody
    public String unique(IndexNews e) throws IOException{
        logger.error("检查文章code的唯一性");
        if(StringUtils.isBlank(e.getCode())){
            throw new NullPointerException("参数不能为空！");
        }
        int c = indexNewsService.selectCount(e);
        return "{\"ok\":\"\"}";
    }

    @Override
    @RequestMapping(value = "toAdd")
    public String toAdd(IndexNews e, ModelMap model) throws Exception {
        String type = e.getType();
        e.clear();
        e.setType(type);
        model.addAttribute("e", e);
        model.addAttribute("catalogsArticle", SystemManager.getInstance().getCatalogsArticle());
        return page_toAdd;
    }

    @Override
    protected void selectListAfter(PagerModel pager) {
        pager.setPagerUrl("selectList");
        RequestHolder.getRequest().setAttribute("catalogsArticle", SystemManager.getInstance().getCatalogsArticle());
    }


}
